package org.Lin.controller;

import org.Lin.service.AdminService;
import org.json.JSONObject;

import java.io.*;
import java.net.Socket;

public class AdminController extends BaseController {

    private final AdminService adminService = new AdminService();

    public void handleAdminOperation(JSONObject request, Socket socket) throws IOException {
        String operation = request.getString("operation");
        int adminID = request.getInt("adminID");

        switch (operation) {
            case "delete_user":
                int targetUserID = request.getInt("targetUserID");
                boolean deleteSuccess = adminService.deleteUser(targetUserID, adminID);
                if (deleteSuccess) {
                    sendSuccess(socket, "用户删除成功");
                } else {
                    sendError(socket, "删除失败：权限不足或用户不存在");
                }
                break;
            case "change_user_status":
                int targetUserId = request.getInt("targetUserID");
                String newStatus = request.getString("newStatus");
                boolean changeSuccess = adminService.changeUserStatus(targetUserId, newStatus, adminID);
                if (changeSuccess) {
                    sendSuccess(socket, "用户状态修改成功");
                } else {
                    sendError(socket, "状态修改失败");
                }
                break;
            default:
                sendError(socket, "未知操作");
                break;
        }
    }

    private void sendSuccess(Socket socket, String message) throws IOException {
        JSONObject response = createSuccessResponse(message);
        sendResponse(socket, response);
    }

    private void sendError(Socket socket, String message) throws IOException {
        JSONObject response = createErrorResponse(message);
        sendResponse(socket, response);
    }

    private void sendResponse(Socket socket, JSONObject response) throws IOException {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(response.toString());
    }
}
